/*
 * @Description:
 * @version:
 * @Author: 潘骏杰
 * @Date: 2021-11-19 09:03:57
 * @LastEditors: 周子尧
 * @LastEditTime: 2022-04-11 10:30:33
 */
import axios from 'axios'
import { Notify } from 'vant'

import sha1 from 'js-sha1'
import CryptoJS from '@/utils/CryptoJS'

// let appkeyby = CryptoJS.encrypt(appkey)
// let appkeyold = CryptoJS.decrypt(appkeyby)
// console.log(appkeyby);
// console.log(appkeyold);

// let appsecretby = CryptoJS.encrypt(appsecret)
// let appsecretold = CryptoJS.decrypt(appsecretby)
// console.log(appsecretby);
// console.log(appsecretold);

// let signature = sha1('123123')//vue
// console.log(signature)
const baseURL =
  process.env.NODE_ENV === 'development' ? '/api' : window.productionUrl
// const baseURL = '/api'
// console.log(process.env)
// 创建axios实例
const service = axios.create({
  baseURL, // api的base_url  window.productionUrl
  withCredentials: true,
  timeout: 30000 // 请求超时时间
})

// 发送请求拦截器
service.interceptors.request.use(
  (config) => {
    const Nonce =
      Math.ceil(+new Date() / 1000) + '' + Math.ceil(Math.random() * 10000)
    const CurTime = Math.floor(+new Date() / 1000).toString()
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'

    if (window.localStorage.getItem('appKey')) {
      window.appKey = window.localStorage.getItem('appKey')
      window.appsecret = 'pgykou9tl6c5es73bmfw47s0qxm6eijp'
    } else {
      window.appKey = '81g777ajqo8lk7cy2uiyedf5gf855ssd1'
      window.appsecret = 'opkjjs7wb6c5ee12xxfw23d0rxd5eqwe'
    }
    const appkey = window.appKey
    const appsecret = window.appsecret
    let hasTokenObj
    // console.log(hasTokenObj);
    const sureHas = window.localStorage.getItem('bodyObj') || undefined
    if (sureHas) {
      hasTokenObj = JSON.parse(CryptoJS.decrypt(sureHas))
      // console.log(hasTokenObj);
    }
    if (hasTokenObj) {
      // console.log("有");
      config.headers['Authorization'] =
        hasTokenObj.tokeType + ' ' + hasTokenObj.accessToken
    } else {
      // console.log("无");
      config.headers['appKey'] = appkey
    }

    config.headers['nonce'] = Nonce
    config.headers['curTime'] = CurTime
    config.headers['ReqUseAlgo'] = 'base64'
    // console.log(appsecret + Nonce + CurTime + "base64");
    config.headers['checkSum'] = sha1(appsecret + Nonce + CurTime + 'base64')

    const params = config.data
    // console.log("------------打包webpack自动去掉-------------------------");
    // console.log(params);
    const jiami = CryptoJS.encrypt(JSON.stringify(params))
    // let jiami = params;
    config.data = jiami
    // console.log("加密：")
    // console.log(jiami);
    // let jiemi = CryptoJS.decrypt(jiami);
    // console.log('转换byte:')
    // console.log(jiemi);

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 发送请求响应拦截
service.interceptors.response.use(
  (response) => {
    const res = JSON.parse(CryptoJS.decrypt(response.data))
    // 错误的status情况
    // console.log(res);
    if (!res.result) {
      Notify({ type: 'danger', message: res.message || 'error' })
      // if (window.localStorage.getItem("loginToken")) {
      //   Notify({ type: "danger", message: res.message || "error" });
      // } else {
      //   router.replace({ path: "/login", query: { ak: router.query.ak } });
      // }

      // 其他的code 需要单独判断
      //       //501 token匹配失败，回到登录

      // if (response.code == 501) {
      //   // ??? 需要单独调试一番
      //   store.dispatch('user/backToLogin').then(() => {
      //     //location.reload()
      //   })
      // }

      return Promise.reject(res.message || 'error')
    } else {
      return res
    }
  },
  (error) => {
    // console.log("err" + error);
    // if (error.response.status == 500) {
    //   location.reload()
    // }
    Notify({ type: 'danger', message: error.message || 'error' })
    return Promise.reject(error)
  }
)

export default service
